<template>
  <a-modal destroyOnClose :title="postIndex == 1 ? '岗位新增' : '岗位编辑'" width="1060px" :visible="visible" @cancel="handleClose">
    <a-form-model ref="ruleFormModel" :model="formModel" :rules="rulesModel" :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }" style="padding-right: 60px">
      <title-name title="基本信息"></title-name>
      <a-row :gutter="24">
        <a-col :md="12" :sm="12">
          <a-form-model-item label="岗位名称" prop="name" class="requiredFormItem">
            <BaseInput v-model="formModel.name" placeholder="请输入"></BaseInput>
          </a-form-model-item>
        </a-col>
        <a-col :md="24" :sm="24">
          <a-form-model-item label="关联标准岗位" prop="basePostId" class="requiredFormItem" :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }">
            <a-tree-select
              tree-node-filter-prop="title"
              v-model="formModel.basePostId"
              :treeData="relationOrgs"
              :replaceFields="{ key: 'id', value: 'id' }"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :treeDefaultExpandedKeys="basePostExpandedKeys"
              placeholder="请选择关联标准岗位"
              :load-data="onLoadRelationData"
              treeNodeLabelProp="label"
            >
              <a-icon v-if="basePostLoading" slot="suffixIcon" type="loading" />
            </a-tree-select>
          </a-form-model-item>
        </a-col>
        <a-col :md="12" :sm="12">
          <a-form-model-item label="岗位编码" prop="code" class="requiredFormItem">
            <BaseInput v-model="formModel.code" disabled placeholder="请输入"></BaseInput>
          </a-form-model-item>
        </a-col>
        <a-col :md="12" :sm="12">
          <a-form-model-item label="岗位标签" prop="postLabelName" class="requiredFormItem">
            <!-- <a-select v-model="formModel.postLabelIds" disabled placeholder="请选择">
              <a-select-option v-for="item in postList" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
            </a-select> -->
            <BaseInput v-model="formModel.postLabelName" disabled placeholder="请输入"></BaseInput>
          </a-form-model-item>
        </a-col>
        <a-col :md="12" :sm="12">
          <a-form-model-item label="是否是领导" prop="isLeader" class="requiredFormItem">
            <a-select v-model="formModel.isLeader" placeholder="请选择">
              <a-select-option v-for="item in isLeaderList" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :md="12" :sm="12">
          <a-form-model-item label="状态" prop="enable" class="requiredFormItem">
            <a-select placeholder="请选择" v-model="formModel.enable">
              <a-select-option v-for="(item, index) in state" :value="item.value" :key="index">{{ item.name }}</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
    <template slot="footer" style="text-align: right">
      <a-button :loading="loading" type="primary" @click="handleSubmitPost">提交</a-button>
      <a-button type="default" class="ml12" @click="handleClose">关闭</a-button>
    </template>
  </a-modal>
</template>

<script>
import ACol from 'ant-design-vue/es/grid/Col'
import ARow from 'ant-design-vue/es/grid/Row'
import { isLeaderList, type } from './model'
import { editPostManageList2, addPostByCompany, pageByBasePost } from '@/api/system/system'
import { getCustOrgTree } from '@/api/subassembly/TreeSelectOrganization'
import { generateList, findNodeFromTree, setNodeInTree } from '@/utils/util'

export default {
  name: 'addEditPost',
  components: {
    ARow,
    ACol
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    postInfo: {
      type: Object,
      default() {
        return {}
      }
    },
    postIndex: {
      type: Number,
      default: 1
    },
  },
  data() {
    return {
      //状态信息
      state: [
        { name: '可用', value: 1 },
        { name: '不可用', value: 0 }
      ],
      relationOrgs: [],
      relationOrgsList: [],
      rulesModel: {
        name: [{ required: true, message: '请输入', trigger: 'blur' }],
        basePostId: [{ required: true, message: '请选择', trigger: 'change' }],
        isLeader: [{ required: true, message: '请选择', trigger: 'change' }],
        enable: [{ required: true, message: '请选择', trigger: 'change' }]
      },
      loading: false,
      basePostLoading: false,
      isLeaderList,
      type,
      formModel: {
        name: '',
        basePostId: '',
        code: '',
        postLabelIds: '',
        postLabelName: '',
        isLeader: 0,
        enable: null
      },
      basePostExpandedKeys: [],
    }
  },
  watch: {
    visible: {
      handler(val){
        if(val){
          Object.keys(this.formModel).forEach(key => {
            if(key === 'postLabelIds' && this.postInfo.postLabelIds instanceof Array){
              this.formModel[key] = this.postInfo[key].join(',')
            }else{
              this.formModel[key] = this.postInfo[key]
            }
          })
          this.getOrgTree()
        }
      }
    },
    'formModel.basePostId': {
      handler(){
        this.setFormDataFromOrgId()
      }
    },
  },
  methods: {
    getOrgTree(){
      // 关联标准组织树
      this.basePostLoading = true
      getCustOrgTree({
        baseOrgType: 1,
        // containVirtual: 0
      }).then(res => {
        if(res.status == 200){
          this.relationOrgs = this.filterLeaderTree(res.data)
          this.relationOrgsList = generateList(res.data)
          this.setFormDataFromOrgId()
          if(this.postInfo.basePostOrgId){
            const dataRef = findNodeFromTree(this.relationOrgs, { key: 'id', value: this.postInfo.basePostOrgId})
            if(dataRef){
              this.onLoadRelationData({ dataRef })
            }
          }else{
            this.basePostLoading = false
          }
        }
      })
    },
    filterLeaderTree(treeData, titlePath) {
      return treeData.map(item => {
        let label = titlePath?`${titlePath}/${item.label}`:item.label;
        if(item.children && item.children.length){
          return {
            ...item,
            disabled: true,
            title: item.label,
            label,
            children: this.filterLeaderTree(item.children, label)
          }
        }else{
          return {
            ...item,
            disabled: true,
            title: item.label,
            label,
          }
        }
      })
    },
    filterRelationOrgs(treeData){
      return treeData.map(item => {
        if(item.children && item.children.length){
          return {
            ...item,
            disabled: true,
            children: this.filterRelationOrgs(item.children)
          }
        }else{
          return {
            ...item,
            disabled: true,
          }
        }
      })
    },
    findParentIds(treeData, id){
      const ids = []
      const list = generateList(treeData)
      const fun = (parentId) => {
        const findItem = list.find(item => item.id === parentId || item.data?.id === parentId)
        if(findItem){
          ids.push(findItem.id || findItem.data?.id)
          if(findItem.parentId || findItem.data?.parentId){
            fun(findItem.parentId || findItem.data?.parentId)
          }
        }
      }
      fun(id)
      return ids
    },
    setFormDataFromOrgId(){
      const org = this.relationOrgsList.find(item => item.id === this.formModel.basePostId)
      if(org){
        this.formModel = {
          ...this.formModel,
          code: org.data.code,
          postLabelName: org.data.postLabelName,
          postLabelIds: org.data.postLabelIds ? org.data.postLabelIds.join(',') : '',
        }
      }
    },
    onLoadRelationData({ dataRef }){
      return new Promise((resolve) => {
        if((dataRef.data.type == 2 || dataRef.data.type == 7) && (!dataRef.children || !dataRef.children.length)){
          pageByBasePost({
            orgId: dataRef.id,
            orgCode: dataRef.code,
            pageIndex: 1,
            pageSize: 9999
          }).then(res => {
            if(this.basePostLoading) this.basePostLoading = false
            if(res.status == 200){
              dataRef.children = res.data.list.map(item => ({
                data: {
                  ...item,
                  parentId: item.orgId,
                },
                id: item.id,
                label: dataRef.label+'/'+item.name,
                title: item.name,
                isLeaf: true,
                disabled: item.enable == 0
              }))
              this.relationOrgsList = generateList(this.relationOrgs)
              if(this.formModel.basePostId){
                this.basePostExpandedKeys = this.findParentIds(this.relationOrgs, this.formModel.basePostId)
              }
              this.$forceUpdate()
            }
            resolve()
          })
        }else{
          resolve()
        }
      })
    },
    /**
     *@desc 提交表单
     *@param {}
     */
    handleSubmitPost() {
      setTimeout(() => {
        this.loading = false
      }, 2000);
      this.$refs.ruleFormModel.validate((valid) => {
        if (valid) {
          if (this.loading) {
            return
          }
          this.loading = true
          let index = this.postIndex
          if (index === 1) {
            //用户新增
            this.handleAddPost()
          } else if (index === 2) {
            //用户编辑
            this.handleEditPost()
          }
        } else {
          return false
        }
      })
    },
    /**
     *@desc table 新增
     *@param {}
     */
    handleAddPost() {
      addPostByCompany({
        ...this.formModel,
        orgId: this.postInfo.orgId,
        postLabelIds: undefined,
      })
        .then((res) => {
          if(res.data.msg){
            this.$notification.warning({
              message: res.data.msg,
            })
          }else if (res.status === 200) {
            // 岗位新增成功
            this.$message.success('新增成功')
            this.$emit('submit')
            this.handleClose()
            this.loading = false
          }
        })
        .catch((err) => {
          this.loading = false
          // 岗位新增失败
          console.log(err)
        })
    },
    /**
     *@desc table 编辑
     *@param {}
     */
    handleEditPost() {
      editPostManageList2({
        ...this.formModel,
        id: this.postInfo.id,
        orgId: this.postInfo.orgId,
        postLabelIds: undefined,
      })
        .then((res) => {
          if(res.data.msg){
            this.$notification.warning({
              message: res.data.msg,
            })
          }else if (res.status === 200) {
            // 岗位编辑成功
            this.$message.success('编辑成功')
            this.$emit('submit')
            this.handleClose()
            this.loading = false
          }
        })
        .catch((err) => {
          // 岗位编辑失败
          this.loading = false
        })
    },
    /**
     *@desc 重置表单
     *@param {}
     */
    handleReset() {
      this.$refs.ruleFormModel.resetFields()
    },
    /**
     *@desc 关闭用户新增
     *@desc 返回用户管理
     *@param {}
     */
    handleClose() {
      // this.handleReset();
      this.$emit('cancel')
    }
  }
}
</script>

<style scoped>
/* .base-post{
  background-color: #FFF9E8;
  border-color: #e4ac0b;
} */
.base-post>.ant-select-selection--single{
  background-color: #FFF9E8 !important;
  border-color: #e4ac0b !important;
}
</style>